//
//  DigitNoteViewController.m
//  NewApp
//
//  Created by  on 12-7-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DigitNoteViewController.h"
#import "NAStyledTableViewCell.h"
#import "DigitNoteDetailsViewController.h"
#import "DigitNoteSearchResultViewController.h"


@interface DigitNoteViewController ()

@end

@implementation DigitNoteViewController
@synthesize selectedIndexPath;

#pragma mark -
#pragma mark - Views lifecycle and memory managment

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //Send request to retrieve digit note
    [self loadRequest];
    [self.view setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //Use table style only
    [self.view addSubview:self.tableView];
    _searchBar = [[NASearchBar alloc] initWithFrame:CGRectMake(0.f, 0.f, 320.f, 44.f)];
    _searchBar.delegate = self;
    [self.tableView setTableHeaderView:_searchBar];
    
    self.title = @"返回";
    self.tabBarItem.title = @"電子型錄";
}

- (void) dealloc {
    [selectedIndexPath release];
    [_searchBar release];
    [super dealloc];
}

- (void) deselectedCell:(UITableViewCell *) cell {
    [cell setSelected:NO animated:YES];
}

#pragma mark -
#pragma mark - UITableView delegate

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
     NAStyledTableViewCell *cell = (NAStyledTableViewCell *) [self.tableView cellForRowAtIndexPath:indexPath];
    if (cell) {
        [self performSelector:@selector(deselectedCell:) withObject:cell afterDelay:0.2f];
        
    }
    
    NACategory *category = (NACategory *)[self entityAtIndex:indexPath.row];
    if (category != nil) {
        if (category.subCategory != nil && category.subCategory.count > 0) {
            
            if (!category.isExpanded) {
                self.selectedIndexPath = [indexPath retain];
                
                NSInteger rowIndex = indexPath.row;
                NSMutableArray *indexPathToInsert = [[NSMutableArray alloc] init];
                for (NACategory *cat in category.subCategory) {
                    rowIndex++;
                    [self.datasourceObjects insertObject:cat atIndex:rowIndex];
                    [indexPathToInsert addObject:[NSIndexPath indexPathForRow:rowIndex inSection:0]];
                }
                
                if (indexPathToInsert.count > 0 ) {
                    [self.tableView beginUpdates];
                    [self.tableView insertRowsAtIndexPaths:indexPathToInsert 
                                          withRowAnimation:UITableViewRowAnimationBottom];
                    [self.tableView endUpdates];
                }
                
                [indexPathToInsert release];
                category.isExpanded = YES;
                
                NAStyledTableViewCell *cell = (NAStyledTableViewCell *) [self.tableView cellForRowAtIndexPath:indexPath];
                cell.isExpanded = YES;
                [cell performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:NO];

                
            }else {
                self.selectedIndexPath = nil;
                NSMutableArray *indexPathToDelete = [[NSMutableArray alloc] init];
                NSInteger rowIndex = indexPath.row;
                for (NACategory *cat in category.subCategory) {
                    rowIndex++;
                    [self.datasourceObjects removeObject:cat];
                    [indexPathToDelete addObject:[NSIndexPath indexPathForRow:rowIndex inSection:0]];
                }
                
                if (indexPathToDelete.count > 0 ) {
                    [self.tableView beginUpdates];
                    [self.tableView deleteRowsAtIndexPaths:indexPathToDelete
                                          withRowAnimation:UITableViewRowAnimationBottom];
                    [self.tableView endUpdates];
                }
                
                [indexPathToDelete release];
                category.isExpanded = NO;
                
                NAStyledTableViewCell *cell = (NAStyledTableViewCell *) [self.tableView cellForRowAtIndexPath:indexPath];
                cell.isExpanded = NO;
                [cell performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:NO];

            }
        }
        else {
//            DigitNoteDetailsViewController *viewCtrl = [[DigitNoteDetailsViewController alloc] initWithCategory:category];
//            [self.navigationController pushViewController:viewCtrl animated:YES];
//            [viewCtrl release]; 
            [self viewDetailsWithCategory:category];
        }
    }
}

#pragma mark -
#pragma mark - UITableView datasource

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datasourceObjects.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView 
          cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cellidentifier";
    NAStyledTableViewCell *cell = (NAStyledTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[NAStyledTableViewCell alloc] initWithNAStyle:self.currentStyle reuseIdentifier:cellIdentifier];
    }
    
    NACategory *cate = [self.datasourceObjects objectAtIndex:indexPath.row];
    cell.sID = cate.sID;
    cell.name = cate.title;
    cell.isChild = cate.isChild;
    cell.isExpanded = cate.isExpanded;
    cell.showsAccessory = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //cell.selectionStyle = UITableViewCellSelectionStyleGray;
    if (self.selectedIndexPath != nil && cell.isChild && indexPath.row > self.selectedIndexPath.row) {
        cell.backgroundImage = (self.selectedIndexPath.row %2 == 0) ? [UIImage imageNamed:@"news_list_B_item_bg_1.png"] : [UIImage imageNamed:@"news_list_B_item_bg_2.png"];
        
    }else {
        cell.backgroundImage = (indexPath.row %2 == 0) ? [UIImage imageNamed:@"news_list_B_item_bg_1.png"] : [UIImage imageNamed:@"news_list_B_item_bg_2.png"];
    }
    
    [cell update];
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.f;
}

#pragma mark -
#pragma mark - Override methods

- (void) requestDidFinished:(RequestEngine *)reqEngine withObject:(id)object {
    if ([object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *result = (NSDictionary *) object;
        [result retain];
        
        self.titleLabel.text = [result objectForKey:@"top_title"];
        self.currentStyle = ([result objectForKey:kStyle] == nil) ? @"D" : [result objectForKey:kStyle];
        NSArray *dataArray = [result objectForKey:kData];
        for (NSDictionary *dict in dataArray) {
            NACategory *category = [[NACategory alloc] initWithDictionary:dict];
            [self.datasourceObjects addObject:category];
        }
        
        [self.tableView reloadData];
        
        [result release];
    }

}

#pragma mark -
#pragma mark - NASearchBarDelegate methods

- (void) searchButtonDidPressed {
    if (_searchBar.keywordTextfield.text.length == 0) 
        return;
    
    DigitNoteSearchResultViewController *viewCtrl = [[DigitNoteSearchResultViewController alloc] initWithID:nil keyword:_searchBar.keywordTextfield.text];
    [self.navigationController pushViewController:viewCtrl animated:YES];
    [viewCtrl release];
    
}

#pragma mark -
#pragma mark - Public methods

- (void) loadRequest {
    [self.engine digitNoteInfos];
}

- (void) viewDetailsWithCategory:(NACategory *) cat {
    if (nil == cat) 
        return;
    self.title = @"返回";
    DigitNoteDetailsViewController *viewCtrl = [[DigitNoteDetailsViewController alloc] initWithCategory:cat];
    [self.navigationController pushViewController:viewCtrl animated:YES];
    [viewCtrl release]; 
}

@end
